import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {CONST} from "../../common/const";
import {Helper} from "../../common/Helper";
import {ControlsCheck} from "../../common/controlsCheck";
import {UserProvider} from "../../providers/user/user";

@Component({
  selector: 'page-login-password',
  templateUrl: 'login-password.html',
})
export class LoginPasswordPage {

  form: FormGroup
  canSub: Boolean = true

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private cc: ControlsCheck,
              private helper: Helper,
              private user: UserProvider,
              private fb: FormBuilder) {
    this.createForm()
  }

  createForm() {
    this.form = this.fb.group({
      oldPassword: ['', Validators.compose([Validators.required, Validators.pattern(CONST.REG_PASSWORD)])],
      newPassword: ['', Validators.compose([Validators.required, Validators.pattern(CONST.REG_PASSWORD)])],
      newPasswordConfirm: ['', Validators.compose([Validators.required, Validators.pattern(CONST.REG_PASSWORD)])],
    })
  }

  submit() {
    if (this.form.controls.newPassword.value !== this.form.controls.newPasswordConfirm.value) {
      this.cc.toastMsg('两次输入的密码不一致')
      return
    }
    if (this.form.valid) {
      if (this.canSub) {
        this.canSub = false
        this.user.setLoginPassword({
          data: this.form.value,
          success: () => {
            this.helper.alert({
              title: '修改成功',
              cssClass: 'g-alert-custom',
              enableBackdropDismiss: false,
              buttons: [{
                text: '确认',
                handler: () => {
                  this.navCtrl.pop()
                }
              }]
            })
          }
        })
      }
      else return false
    } else {
      this.cc.check(this.form.controls, {
        oldPassword: '请输入原始密码',
        newPassword: '密码需由6-20位数字、字母组合'
      })
    }
  }

}
